import cssutils
import requests
from lxml import html
import logging
from src.appointment_ticket import AppointmentTicket
from src.img_upload import ImgUpload

cssutils.log.setLog(logging.getLogger('cssutils'))
cssutils.log.setLevel(logging.CRITICAL)

cookies = {
    '.AspNetCore.Antiforgery.BDmv0qjjHrI': 'CfDJ8ItFsDhqkWRIiWYGIDDs_SOC0gifWnzkwgogDLPldOR9pHlFoBtc29VVLzNg7Qzg8xDNh8JAPoXjjcr3kU5rIPtDwqy1A9Xt34mbEHHfJX02mZv-e-KXvokkXkbj9IWtHlCgAuQH6-FbLZfUu20vIE4',
    '.AspNetCore.Cookies': 'CfDJ8ItFsDhqkWRIiWYGIDDs_SPTMLi1uNsxNOHWikckiouC3ZpOdWcVtndYWHy8jKZ-R_0eCFVdrQUW2N_HwfTcDGinjI8qg2CzPsMFQuvEwP8ePkfU5ScfMoolkJenpa4iwBtoQneRyXilpACP5GH7EqBJJoIP-fEgVv35HXbiyKjju4yE_aoZ9JRAJPGbobYRAXhpmR9CckLsAd9pBI6YFTyH1EQcOiQKsCNar3pd7E-Nq2cPMq3_lSMz-1gR1VCPHQ-drnrSv2arqVNC2ImxobmNpO9tPYdele7SUw21508pZZtUAKgGMN4J7ZGTX71NDdF4F5EDXIL939XEkHv-xvEB5kWeq9nuiruR4mfFz6W28cLeGH34h9eEe-xSnwFxcoPev4qqXib-wpKsnAlBv73apxlLim0gsNI0ahMQtRaDxAzsHJlYhaTBAKaWhhWIeJKsI5mDhAoMdavc3vhwNYWbBacBe4h40hBbpkjtTvH1dEkwV6MJla3pPsWCtv_LQTeDr5EZ-xpaMMKh-U6ELPCoyPx4VLlzGbU1YbQbOt2Mf5KpDIZWyx9t21BI0eZLFcJ8QZWr1pecHE1F28WLbxf1lc5oJcp1Ta3Lk5GrU4Br6pb3RuKcXGIFjkJU6I2mCnyzwUgCz3IBGwMoWnblXbbZ2L16obLrMpt7ak5MN_DwUCHnFQ3waCkPUcprmdj3R8XRmCUbj4umQGeOdMdNuRzvaVjct1yu4_p4xDJ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zWUVnWeSDl7MI9i9uRw',
        'X-Requested-With': 'XMLHttpRequest'
    }
    url = 'https://spain.blscn.cn/CHN/bls/VisaTypeVerification'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/122.0.0.0 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'
    }
    res = requests.post(url, headers=headers, cookies=cookies, data=data)
    print(res.status_code)
    if res.status_code == 200:
        result_json = res.json()
        if result_json['success']:
            print('https://spain.blscn.cn' + res.json()['returnUrl'])
            headers = {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,'
                          '*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
                'Accept-language': 'zh,en-GB;q=0.9,en;q=0.8,zh-CN;q=0.7',
                'Accept-Encoding': 'gzip, deflate, br, zstd',
                'Cache-Control': 'no-cache',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                              'Chrome/122.0.0.0 Safari/537.36',
                'Referer': 'https://spain.blscn.cn/CHN/Bls/VisaTypeVerification',
                'Pragma': 'no-cache',
                'Sec-Ch-Ua': 'Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
                'Sec-Ch-Ua-Mobile': '?0',
                'Sec-Ch-Ua-Platform': 'Windows',
                'Sec-Fetch-Dest': 'document',
                'upgrade-insecure-requests': '1'
            }

            res = requests.get('https://spain.blscn.cn' + res.json()['returnUrl'], headers=headers, cookies=cookies)
            tree = html.fromstring(res.content)
            __RequestVerificationToken = tree.xpath('//input[@name="__RequestVerificationToken"]')[0].get('value')
            CaptchaData = tree.xpath('//input[@id="CaptchaData"]')[0].get('value')
            ScriptData = tree.xpath('//input[@id="ScriptData"]')[0].get('value')
            VisaType = "3033c6d3-579b-47e1-9602-91368d63025c"
            AppointmentCategoryId = "5c2e8e01-796d-4347-95ae-0c95a9177b26"
            VisaSubType = "d6f2b878-181f-4584-a595-babdbcac4298"
            Location = "8d780684-1524-4bda-b138-7c71a8591944"

            style_tags = tree.xpath('//style')
            stylesheet = cssutils.parseString(style_tags[1].text)
            displayList = get_css_properties(stylesheet)
            index = get_form_index(tree, displayList)

            data = {"Mission1": "", "Mission2": "", "Mission3": "", "Mission4": "", "Mission5": "",
                    "AppointmentFor1": "Individual", "AppointmentFor2": "Individual", "AppointmentFor3": "Individual",
                    "AppointmentFor4": "Individual", "AppointmentFor5": "Individual", "ApplicantsNo1": "",
                    "ApplicantsNo2": "", "ApplicantsNo3": "", "ApplicantsNo4": "", "ApplicantsNo5": "", "VisaType1": "",
                    "VisaType2": "", "VisaType3": "", "VisaType4": "", "VisaType5": "", "AppointmentCategoryId1": "",
                    "AppointmentCategoryId2": "", "AppointmentCategoryId3": "", "AppointmentCategoryId4": "",
                    "AppointmentCategoryId5": "", "VisaSubType1": "", "VisaSubType2": "", "VisaSubType3": "",
                    "VisaSubType4": "", "VisaSubType5": "", "Location1": "", "Location2": "", "Location3": "",
                    "Location4": "", "Location5": "", "CaptchaData": CaptchaData, "ScriptData": ScriptData,
                    "ResponseData": "", "__RequestVerificationToken": __RequestVerificationToken,
                    "X-Requested-With": "XMLHttpRequest", 'VisaType' + index: VisaType,
                    'AppointmentCategoryId' + index: AppointmentCategoryId, 'VisaSubType' + index: VisaSubType,
                    'Location' + index: Location}

            url = 'https://spain.blscn.cn/CHN/bls/VisaType'
            res = requests.post(url, headers=headers, cookies=cookies, data=data)
            result_json = res.json()
            if result_json['success']:
                headers = {
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,'
                              '*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
                    'Accept-language': 'zh,en-GB;q=0.9,en;q=0.8,zh-CN;q=0.7',
                    'Accept-Encoding': 'gzip, deflate, br, zstd',
                    'Cache-Control': 'no-cache',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                                  'Chrome/122.0.0.0 Safari/537.36',
                    'Referer': 'https://spain.blscn.cn/CHN/Bls/VisaTypeVerification',
                    'Pragma': 'no-cache',
                    'Sec-Ch-Ua': 'Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
                    'Sec-Ch-Ua-Mobile': '?0',
                    'Sec-Ch-Ua-Platform': 'Windows',
                    'Sec-Fetch-Dest': 'document',
                    'upgrade-insecure-requests': '1'
                }

                res = requests.get('https://spain.blscn.cn' + res.json()['returnUrl'], headers=headers, cookies=cookies)
                tree = html.fromstring(res.content)


def get_css_properties(sheet):
    # 创建一个字典来保存属性
    display_list = []
    # 遍历所有的规则
    for rule in sheet:
        if rule.type == rule.STYLE_RULE:
            for property in rule.style:
                if property.name == 'display' and property.value == 'block':
                    display_list.append(rule.selectorText)

    return display_list


def get_display_properties(sheet, display_list):
    # 遍历所有的规则
    for rule in sheet:
        # 如果规则应用于我们感兴趣的类
        for display in display_list:
            rule_id = rule['id'][1:] + ' '
            if rule_id in display['class_name']:
                display['display'] = rule['display']


def get_form_index(tree, displayList):
    for i in range(5):
        VisaType = tree.xpath('//input[@id="VisaType' + str(i + 1) + '"]/..')[0].get('class')
        for tt in VisaType.split(' '):
            if '.' + tt in displayList:
                return str(i + 1)


if __name__ == '__main__':
    # get_create_env(cookies)
    # with open('./test.html', 'r', encoding='utf-8') as file:
    #     content = file.read()
    #
    # VisaType = "3033c6d3-579b-47e1-9602-91368d63025c"
    # AppointmentCategoryId = "5c2e8e01-796d-4347-95ae-0c95a9177b26"
    # VisaSubType = "d6f2b878-181f-4584-a595-babdbcac4298"
    # Location = "8d780684-1524-4bda-b138-7c71a8591944"
    # AppointmentDate = '2024-04-05'
    # AppointmentSlot = '08:00-08:30'
    #
    # ticket = AppointmentTicket(content, AppointmentDate, AppointmentSlot, cookies)
    # ticket.create()

    # with open('header.png', 'rb') as f:
    #     uplader = ImgUpload(cookies, 'CfDJ8ItFsDhqkWRIiWYGIDDs_SN2OXmS97DVn7CH7j6y-qcl0QNX48p2ert1lc-N7bnhx0KBWMs5HYKsnWLiuDOD8RPFF4yUzbAAmjfPVOsANZZ9GF8Om3vNrqaT016-LEiLtqjxd3sjybcTlcz40HKfDtEXxXoKxueTPMtsCDmR5zIUD6RMR3bbFrOhratvtYG2Lg')
    #     uplader.upload(f)

